package com.jiajia.study.nio.chapter03;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class Worker implements Runnable {


    private String name;

    private Thread thread;

    private Selector selector;

    public Worker(String name) {
        this.name = name;
    }

    public void register(SocketChannel socketChannel) throws IOException {

        thread = new Thread(this,this.name);
        thread.start();
        selector = Selector.open();

        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    @Override
    public void run() {
        while(true){
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while(iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    if(selectionKey.isReadable()){
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        int read = socketChannel.read(byteBuffer);
                        if(read == -1){
                            selectionKey.cancel();
                            socketChannel.close();
                        }
                        byteBuffer.flip();
                        // 解析数据,最好对 bytebuffer 做处理，半包粘包的处理
                        System.out.println(StandardCharsets.UTF_8.decode(byteBuffer).toString());
                        byteBuffer.rewind();
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
